package com.athuawei.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁; 递归锁
 */
public class SyncLockDemo {

    public synchronized void add() {
        add();
    }


    public static void main(String[] args) {

        //lock 演示可重入锁
        Lock lock = new ReentrantLock();
        //创建线程
        new Thread(()->{
            try{
                //上锁
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "外层");

                try{
                    //上锁
                    lock.lock();
                    System.out.println(Thread.currentThread().getName() + "内层");

                } finally {
                    //释放锁
                    lock.unlock();
                }
            } finally {
                //释放锁
                lock.unlock();
            }
        }, "AA").start();

        // 创建一个新线程
        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "新线程");
            } finally {

                lock.unlock();
            }
        }, "BB").start();

        // 2.
//        new SyncLockDemo().add();


        // 1.synchronized
//        Object o = new Object();
//        new Thread(()-> {
//            synchronized (o) {
//                System.out.println(Thread.currentThread().getName() + "外层");
//
//                synchronized (o) {
//                    System.out.println(Thread.currentThread().getName() + "中层");
//
//                    synchronized (o) {
//                        System.out.println(Thread.currentThread().getName() + "内层");
//                    }
//                }
//            }
//        }, "t1").start();;
    }
}
